//
//  LCNewsHTMLViewController.m
//  JK九酷云头条
//
//  Created by admin on 2018/3/7.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LCNewsHTMLViewController.h"
#import "LCNewsHTMLViewController+WKWebView.h"
#import "UIViewController+LCMBProgressHUD.h"

@interface LCNewsHTMLViewController ()
<WKNavigationDelegate,UIGestureRecognizerDelegate,UIScrollViewDelegate>

///是否阅读Title数组
@property (nonatomic,strong) NSMutableArray *selectedData;

@end

@implementation LCNewsHTMLViewController

- (void)dealloc {
    _webView.scrollView.delegate = nil;
    _webView.navigationDelegate = nil;
    [SVProgressHUD dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self naviBarOne];
    
    [self setupTitleImageView];
    [self setupWebView];
    [self addGestureRecognizerObserverWebElementsWithWebView:_webView];
    [self setupDoubleTapOne];
}
/**
 添加长按手势
 @param webView 监听对象
 */
- (void)addGestureRecognizerObserverWebElementsWithWebView:(WKWebView *)webView
{
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
    [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
    WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [self.webView.configuration.userContentController addUserScript:noneSelectScript];

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(startLongPress:)];
    longPress.delegate = self;
    longPress.minimumPressDuration = 1.5f;
    longPress.numberOfTouchesRequired = 1;
    longPress.cancelsTouchesInView = YES;
    [self.webView addGestureRecognizer:longPress];
}
///设置双击
- (void)setupDoubleTapOne {
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap)];
    singleTap.numberOfTapsRequired = 1;

    UITapGestureRecognizer *doubleTapOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    //表示几个手指点击时 触发事件，默认值为1
    doubleTapOne.numberOfTouchesRequired = 1;
    //几次点击时触发事件 ,默认值为1
    doubleTapOne.numberOfTapsRequired = 2;
    doubleTapOne.delegate = self;
    if([LSZSpecialPackaging isDoubleClickSwitch]) {
        [_webView addGestureRecognizer:singleTap];
        [_webView addGestureRecognizer:doubleTapOne];
        // 双击手势确定监测失败才会触发单击手势的相应操作
        [singleTap requireGestureRecognizerToFail:doubleTapOne];
    }
}
- (void)handleSingleTap {
}
///双击点击方法 利用时间计算间隔判断是否双击事件
- (void)handleDoubleTap:(UITapGestureRecognizer *)swipe{
    
//    NSDate *date = [[NSDate alloc] init];
//        JKLog(@"date = %zd", date.timeIntervalSince1970);
//    if (date.timeIntervalSince1970 - _lastDate.timeIntervalSince1970 < 0.4
//        &&
//        date.timeIntervalSince1970 - _lastDate.timeIntervalSince1970 > 0.1
//        ) {
//        NSLog(@"date = %zd", date.timeIntervalSince1970);
        if([LSZSpecialPackaging isDoubleClickSwitch]) {
            if (!_isDragging) {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
        }
//    }
//    _lastDate = date;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    _isDragging = YES;
    NSLog(@"scrollViewDidEndDragging ");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.55 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _isDragging = NO;
    });
}

// 允许多个手势并发
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}
/** 长按识别代理 */
- (void)startLongPress:(UILongPressGestureRecognizer *)pressSender
{
    if(pressSender.state == UIGestureRecognizerStateBegan){
        
        [self detectQRCodeInWebView:pressSender];
        NSLog(@"1. 开始长按手势");
    }else if(pressSender.state == UIGestureRecognizerStateEnded){
        
        //可以添加你长按手势执行的方法,不过是在手指松开后执行
        NSLog(@"2. 结束长按手势");
    }else if(pressSender.state == UIGestureRecognizerStateChanged){
        
        //在手指点下去一直不松开的状态执行
        NSLog(@"3. 长按手势改变");
    }
}
- (void)detectQRCodeInWebView:(UILongPressGestureRecognizer *)pressSender {
    //长按操作
    UIAlertController *showActionTip =
    [UIAlertController alertControllerWithTitle:nil
                                        message:nil
                                 preferredStyle:UIAlertControllerStyleActionSheet];
    //复制链接地址
    UIAlertAction *ActionCopyHref = [UIAlertAction actionWithTitle:@"Safari" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 调用自带浏览器 Safari
        [[UIApplication sharedApplication] openURL:self.webView.URL];
    }];
    [showActionTip addAction:ActionCopyHref];
    //取消
    UIAlertAction *Canel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [showActionTip addAction:Canel];
    [self presentViewController:showActionTip animated:YES completion:nil];
}

- (void)setupWebView {
//    UIImageView *imageView = [[UIImageView alloc] init];
//    NSURL *url = [NSURL URLWithString:self.news.cover[0]];
//    [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"大的默认图片"]];
//    [self.view addSubview:imageView];
//    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.top.equalTo(self.view);
//        make.height.offset(200);
//    }];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    if (![self.url containsString:@"?usercode=0"]) {
        self.url = [NSString stringWithFormat:@"%@?usercode=%@",self.url,[_UserM usercode]];
    }
    self.webView = [self createWebView:self.webView playUrlStr:self.url];
    _webView.scrollView.delegate = self;
    _webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
//        make.top.equalTo(imageView.mas_bottom);
//        make.left.right.bottom.equalTo(self.view);
    }];
    
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:RGBColor(89, 196, 120)];
    [SVProgressHUD setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
//    [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.87 green:0.87 blue:0.87 alpha:1.00]];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative]; //菊花型的转动
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD dismissWithDelay:15];
}

-(NSMutableArray *)selectedData{
    if (_selectedData == nil) {
        _selectedData = [NSMutableArray array];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"selectedData"] != nil) {
            [_selectedData addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"selectedData"]];
        }
    }
    return _selectedData;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSString *commonHide = [NSString stringWithFormat:@"$('.content .hot2 .item .title').removeClass('title2l');$('.content .hot2 .item .sbtn').hide();"];
    [webView evaluateJavaScript:commonHide completionHandler:^(id _Nullable str, NSError * _Nullable error) {
        NSLog(@"str:%@",str);
    }];
    [SVProgressHUD dismissWithDelay:0.2];
    
    NSString *response = webView.title;
    NSLog(@"response = %@", response);
    if ([response containsString:@"Error"] || [response isEqualToString:@""]) {
        [webView reloadFromOrigin];
    }
    [self.selectedData addObject:response];
    [[NSUserDefaults standardUserDefaults] setObject:self.selectedData.copy forKey:@"selectedData"];
    
    NSArray<WKBackForwardListItem *> *history = [webView.backForwardList backList];
    if (history.count >= 1) {
        [self naviBarMore];
    }else{
        [self naviBarOne];
    }
    
}
///页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    [SVProgressHUD showErrorWithStatus:@"网页加载失败，请稍后重试!"];
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    decisionHandler(WKNavigationActionPolicyAllow);
}

@end
